CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Useful GridView Tips

By Satheesh babu
Posted On Apr 21,2008
Article Rating:
Be first to rate
this article.
No of Comments: 11
Category: ASP.Net
Print this article.

Useful GridView Tips

 

Introduction

Datagrid is one of the most commonly used controls in ASP.Net applications. In ASP.Net 2.0, Datagrid is replaced by GridView control while Datagrid control is still supported. There are large numbers of tasks that can be done through gridview control. This article will help us to achieve some of the handy things that can be done on Gridview control. 

 

Making DropDownList in EditItemTemplate value Selected

By default, EditItemTemplate uses textbox control to edit the value in gridview cells.

Sometimes, we will have requirements where we need to populate dropdownlist in EditItemTemplate in a GridView column and have its corresponding item selected for the edit event. Refer the below figure for a better understanding.

 

 

This was made easy in ASP.Net 2.0 by two way data binding expression.

 

Syntax:

<%# Bind(”expression”) %>

 

The below code can be used to achieve the above said requirement.

 

Template Column Markup:

<asp:TemplateField HeaderText="Roles">

<ItemTemplate>

<%# Eval("Role") %>

</ItemTemplate>

 <EditItemTemplate>

<asp:DropDownList ID="ddlRoles"

 DataSource='<%# GetAllRoles() %>' DataTextField="Role"  DataValueField="RoleID"

SelectedValue='<%# Bind("RoleID") %>' runat="server">

</asp:DropDownList>

</EditItemTemplate>

</asp:TemplateField>

 

The access modifier of the function GetAllRoles() defined in the codebehind class should be public.

 

 

ItemIndex equivalent in Gridview’s RowCommand

We all know that the ItemCommand in Datagrid is equivalent to RowCommand in gridview.

In Datagrid control, when we have a button control in a template column then we can capture the button click event in ItemCommand of the Datagrid. Also, we can get the index of the Datagrid row by e.Item.ItemIndex property in ItemCommand event. The same thing cannot be achieved in gridview like e.Row.RowIndex to get the index of the row in the RowCommand.

To achieve this, we can set the RowIndex to the “CommandArgument” property of the button control from RowDataBound Event. Hence, in RowCommand we can get the RowIndex from the CommandArgument property in RowCommand event. The below code will help us understanding it.

 

protected void gvModerateArticles_RowDataBound(object sender, GridViewRowEventArgs e)

    {

        if (e.Row.RowType == DataControlRowType.DataRow)

        {

Button btnAppr = e.Row.Cells[8].Controls[1] as Button;

btnAppr.CommandArgument = e.Row.RowIndex.ToString();

         }

   }

 

 protected void gvModerateArticles_RowCommand(object sender, GridViewCommandEventArgs e)

    {

        if (e.CommandName == "Approve")

        { 

string artID = gvModerateArticles.Rows[int.Parse(e.CommandArgument.ToString())].Cells[0].Text;

        }

    }

 

Alternatively, we can implement the same by,

 

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)

   {

if (e.CommandName.Equals("Approve"))

{

GridViewRow row = (GridViewRow)((Control)e.CommandSource).Parent.Parent;

string _tempvalue = ((Label)GridViewCategories.Rows[row.RowIndex].FindControl("Label1")).Text;

}

   }

 

 




Making GridView Row selectable using JavaScript

When we want to add Delete, Select functionality to a grid we normally proceed by adding a button/hyperlink for each action. By capturing the ID of the row in each action i.e. in ItemCommand or RowCommand (2.0) we can complete the action. To make users more comfortable we can make the whole gridview row selectable so that we can get rid of Delete and Select button/hyperlink from the grid using Jscript. Refer the below figure.

How to achieve this?

We can simulate the selection of a row by calling Javascript function that makes the background of the clicked row to a different color. Refer the above figure. Also, we will declare a hidden field to populate the ID of selected gridview’s row from javascript. In Select/Delete button click we can get the selected row’s ID from the hidden field and can complete the required action.

 

<asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="False" OnRowDataBound="gvUsers_RowDataBound">

 <Columns>

 <asp:BoundField DataField="Email" HeaderText="Email" ReadOnly="True" />

 <asp:BoundField DataField="FirstName" HeaderText="First Name"

   ReadOnly="True" />

 <asp:BoundField DataField="LastName" HeaderText="Last Name"

 ReadOnly="True" />                                    

  </Columns>

 </asp:GridView>

<!- - Hidden field -- >

<INPUT id="hdnEmailID" type="hidden" value="0" runat="server" NAME="hdnEmailID">

 

Javascript functions:

<script language="javascript">

var lastRowSelected;

var originalColor;

function GridView_selectRow(row, EmailID)

{

      var hdn=document.form1.hdnEmailID;

      hdn.value = EmailID;

      if (lastRowSelected != row)

        {

        if (lastRowSelected != null)

         {

          lastRowSelected.style.backgroundColor = originalColor;

          lastRowSelected.style.color = 'Black'

          lastRowSelected.style.fontWeight = 'normal';

         }

      originalColor = row.style.backgroundColor

      row.style.backgroundColor = 'BLACK'

      row.style.color = 'White'

      row.style.fontWeight = 'normal'

      lastRowSelected = row;

      }

}

 

function GridView_mouseHover(row)

{

    row.style.cursor = 'hand';

}

</script>

 

We can link the javascript function call from Gridview’s Row in RowDataBound Event.

 

protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)

    {

        if (e.Row.RowType == DataControlRowType.DataRow)

        {

            e.Row.ID = e.Row.Cells[0].Text;

            e.Row.Attributes.Add("onclick", "GridView_selectRow(this,'" + e.Row.Cells[0].Text + "')");

            e.Row.Attributes.Add("onmouseover", "GridView_mouseHover(this)");

        }

    }

 

In Select/Delete button click event we can get the id of the row clicked by,

hdnEmailID.Value

 

Thus, we can complete the required action with the id in the hidden variable.

Reference

Selectable Grid in ASP.Net 1.x

 

Downloads

Download source

 

Conclusion

GridView is one of most widely used controls and we can do lots of things with the control. This article enables us to achieve some of the useful tasks on Gridview. Download the source packed with this article and see these tips on action. No change needs to be done to make the source code attached with this article since it uses the database attached in App_Data folder. Unzip the code and hit F5 to run.

Happy Coding!!

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
Very Nice Article.. Its Working
The Code was digested... :) Thanks For this kind of Article

Very Nice Article.. im loving it..
and GetRoles() Function is

Function GetRoles() As DataSet
Try
qry = "SELECT RoleId,RoleName FROM RoleDetails WHERE ProjectID=" & Val(Session("Projectid")) & ""
ds = ExecuteDataset(qry, Session("con"))
Return ds
Catch ex As Exception

End Try
End Function
great
Your article is very helpful. thanks!
RE: how can bind dropdown
The GetRoles() function returns a Datatable that thas RoleID and Role fetched from database. Hence assigning this function to DataSource property and specifying datatextfield and datavaluefield will bind the dropdownlist.

how can bind dropdown
Can you write out the function GetAllRoles() ?
becasue the problem is to find the dropdown which is inside "edittemplate"
test
test
fd
improve
Mr
I was facing problem to bind data in DDL, your code helped me.
Thanks.
Thanks
It's works for me
gridview
i have table with 2 row . i row contain grid view & other part contain a form (that contain some fields that access data from db.) i want tha t when i select any row from gridview, the complete info are show in from fields OR i cantain gridview with 3 fields . when i select any row then select row all data fields are show in single line at same gridview. without using detailsview, formview, datalist ,etc
gridview
hi this is malik,i am using gridview with check box, at the end of grid view a have a button by clicking the button all checked check box rows are deleted its working fine but i want to add another column with edit which contains update,cancel ,for this i used some bound fields and some template fielsds now in button click event i didnt get the values of boundfields how can i get the values of gridview cells that any one help me in advance THNX
DropDownList in EditItemTemplate value Selected
Can you write out the function GetAllRoles() ? thank you